//
//  NSString+Url.m
//  MSHD
//
//  Created by HCreater on 2017/12/5.
//  Copyright © 2017年 HCreater. All rights reserved.
//

#import "NSString+Url.h"

@implementation NSString (Url)

+ (NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
        {
            //找到标签的起始位置
            [scanner scanUpToString:@"&" intoString:nil];
            //找到标签的结束位置
            [scanner scanUpToString:@";" intoString:&text];
            //替换字符
            html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
            }
    //NSString * regEx = @"<([^>]*)>";
    //html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
    return html;
}
//将HTML字符串转化为NSAttributedString富文本字符串
+ (NSAttributedString *)attributedStringWithHTMLString:(NSString *)htmlString
{
    NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) };
    
    NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
    
    return [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
}
//将 &lt 等类似的字符转化为HTML中的“<”等
+ (NSString *)htmlEntityDecode:(NSString *)string
{
    string = [string stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    string = [string stringByReplacingOccurrencesOfString:@"&apos;" withString:@"'"];
    string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"]; // Do this last so that, e.g. @"&amp;lt;" goes to @"&lt;" not @"<"
     
    return string;
}

+ (NSString*)dic2url:(NSDictionary*)dic
{
    NSString* strUrl = @"";
    
    NSArray* keys = [dic allKeys];
    
    if ([keys containsObject:@"token"])
    {
        NSMutableArray* keyMutables = [NSMutableArray arrayWithArray:keys];
        
        NSInteger tokenIndex = [keyMutables indexOfObject:@"token"];
        
        if (tokenIndex != 0)
        {
            [keyMutables exchangeObjectAtIndex:tokenIndex withObjectAtIndex:0];
        }
        
        keys = keyMutables;
    }
    
    for (int keyIndex=0; keyIndex<keys.count; keyIndex++)
    {
        NSString* strKey = keys[keyIndex];
        NSString* strValue = dic[keys[keyIndex]];
        
        if (keyIndex == 0)
        {
            strUrl = [strUrl stringByAppendingString:[NSString stringWithFormat:@"%@=%@", strKey, strValue]];
        }
        else
        {
            strUrl = [strUrl stringByAppendingString:[NSString stringWithFormat:@"&%@=%@", strKey, strValue]];
        }
    }
    
    return strUrl;
}

@end
